package com.ecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ecommerce.common.CommonEnum;
import com.ecommerce.common.ResultBody;
import com.ecommerce.entity.Shop;
import com.ecommerce.entity.User;
import com.ecommerce.entity.UserDetail;
import com.ecommerce.service.ShopService;
import com.ecommerce.service.UserDetailService;
import com.ecommerce.service.UserService;
import com.ecommerce.utils.WrapperUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户Controller
 *
 * @author wang
 */
@RestController
@Api(value = "UserController", tags = {"用户接口"})
@RequestMapping("/user")
@Log4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserDetailService userDetailService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private WrapperUtils wrapperUtils;

    /**
     * 查询用户列表
     *
     * @param user     用户
     * @param pageNum  页码
     * @param pageSize 条数
     * @return 用户列表
     */
    @ApiOperation(value = "查询用户列表", notes = "查询用户列表")
    @PostMapping(value = "/userList")
    public ResultBody userList(@RequestBody(required = false) User user, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> wrapper = wrapperUtils.userWrapper(user);
        wrapper.orderByDesc(User::getCreateTime);
        return ResultBody.ok().data(userService.page(page, wrapper));
    }

    /**
     * 查询用户
     *
     * @param userId 用户id
     * @return 用户和用户详细信息
     */
    @ApiOperation(value = "查询用户", notes = "查询用户")
    @PostMapping(value = "/queryUser")
    public ResultBody queryUser(@RequestParam String userId) {
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getUserId, userId);
        User user = userService.getOne(userWrapper);
        LambdaQueryWrapper<UserDetail> userDetailWrapper = new LambdaQueryWrapper<>();
        userDetailWrapper.eq(UserDetail::getUserId, userId);
        UserDetail userDetail = userDetailService.getOne(userDetailWrapper);
        Map<String, Object> returnMap = new HashMap<>(2);
        returnMap.put("user", user);
        returnMap.put("userDetail", userDetail);
        return ResultBody.ok().data(returnMap);
    }

    /**
     * 创建用户
     *
     * @param user 用户
     * @return 创建用户情况
     */
    @ApiOperation(value = "创建用户", notes = "创建用户")
    @PostMapping(value = "/insertUser")
    public ResultBody insertUser(@RequestBody User user) {
        Long account = user.getAccount();
        if (isUserExist(account)) {
            String ciphertext = DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes());
            user.setUserPassword(ciphertext);
            user.setCreateTime(new Date());
            user.setStatus("1");
            boolean saveUser = userService.save(user);
            boolean saveMessage = saveUserMessage(user);
            if (saveUser && saveMessage) {
                return ResultBody.ok().message("创建用户成功");
            } else {
                return ResultBody.error().message("创建用户失败");
            }
        } else {
            return ResultBody.error().message("用户已存在");
        }
    }

    /**
     * 用户详情
     *
     * @param userDetail userDetail
     * @return 用户详情
     */
    @ApiOperation(value = "用户信息", notes = "用户信息")
    @PostMapping(value = "/userDetail")
    public ResultBody userDetail(@RequestBody UserDetail userDetail) {
        Long userId = userDetail.getUserId();
        if (userId != null) {
            LambdaQueryWrapper<UserDetail> userDetailWrapper = new LambdaQueryWrapper<>();
            userDetailWrapper.eq(UserDetail::getUserId, userId);
            userDetail = userDetailService.getOne(userDetailWrapper);
            if (userDetail != null) {
                return ResultBody.ok().data(userDetail);
            }
            return ResultBody.error().message("该用户不存在");
        }
        return ResultBody.error().message("该用户不存在");
    }

    /**
     * 修改用户信息
     *
     * @param userDetail userDetail
     * @return 修改用户信息
     */
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息")
    @PostMapping(value = "/updateUserDetail")
    public ResultBody updateUserDetail(@RequestBody UserDetail userDetail) {
        LambdaQueryWrapper<UserDetail> userDetailWrapper = new LambdaQueryWrapper<>();
        userDetailWrapper.eq(UserDetail::getUserId, userDetail.getUserId());
        UserDetail one = userDetailService.getOne(userDetailWrapper);
        userDetail.setUserDetailId(one.getUserDetailId());
        boolean update = userDetailService.updateById(userDetail);
        if (update) {
            return ResultBody.ok().message("修改用户信息成功");
        }
        return ResultBody.error().message("修改用户信息失败");
    }

    /**
     * 商家信息
     *
     * @param shop shop
     * @return 商家信息
     */
    @ApiOperation(value = "商家信息", notes = "商家信息")
    @PostMapping(value = "/shopDetail")
    public ResultBody shopDetail(@RequestBody Shop shop) {
        Long shopId = shop.getShopId();
        if (shopId != null) {
            shop = shopService.getById(shopId);
            if (shop != null) {
                return ResultBody.ok().data(shop);
            }
            return ResultBody.error().message("该商家不存在");
        }
        return ResultBody.error().message("该商家不存在");
    }

    /**
     * 修改商家信息
     *
     * @param shop shop
     * @return 修改商家信息
     */
    @ApiOperation(value = "修改商家信息", notes = "修改商家信息")
    @PostMapping(value = "/updateShop")
    public ResultBody updateShop(@RequestBody Shop shop) {
        boolean update = shopService.updateById(shop);
        if (update) {
            return ResultBody.ok().message("修改商家信息成功");
        }
        return ResultBody.error().message("修改商家信息失败");
    }

    /**
     * 判断用户是否存在
     *
     * @param account 手机号
     * @return 判断值
     */
    private boolean isUserExist(Long account) {
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getAccount, account);
        User one = userService.getOne(userWrapper);
        return one == null;
    }

    /**
     * 保存用户 (个人信息/商家信息)
     *
     * @param user 用户
     * @return 保存状态
     */
    private boolean saveUserMessage(User user) {
        boolean saveMessage;
        if (user.getUserType().equals(CommonEnum.USER.getCode())) {
            UserDetail userDetail = new UserDetail();
            userDetail.setUserId(user.getUserId());
            userDetail.setUserAccount(new BigDecimal(0));
            userDetail.setUserPoints(0);
            userDetail.setHistoryPoints(0);
            userDetail.setStatus("0");
            saveMessage = userDetailService.save(userDetail);
        } else {
            Shop shop = new Shop();
            shop.setShopAdmin(user.getUserId());
            shop.setShopPhone(String.valueOf(user.getAccount()));
            shop.setDeleted("0");
            shop.setShopName("默认商家");
            saveMessage = shopService.save(shop);
        }
        return saveMessage;
    }
}
